//
//  VM6EditShareUserVController.m
//  DoorBell
//
//  Created by Chun Hung Cheung on 2024/12/9.
//  Copyright © 2024 Chun Hung Cheung. All rights reserved.
//

#import "CatEditShareUserVController.h"

@interface CatEditShareUserVController ()<UITextFieldDelegate>
@property(nonatomic,strong)UIScrollView *containerScrollview; // 底层的scrollview
@property(nonatomic,strong)UIView *containerView;// 添加到Scrollview 的view
@property(nonatomic,strong)UIView *iconContrainview;// 二维码容器
@property(nonatomic,strong)UIView *bottom_view;// 二维码
@end

@implementation CatEditShareUserVController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setup];
    
    self.iconContrainview.backgroundColor = [UIColor clearColor];
    self.bottom_view.backgroundColor = [UIColor clearColor];
}


- (void)setup
{
    UIButton *settingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
     settingBtn.frame = CGRectMake(0, 0, 160, 20);
     settingBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18.0];
    [settingBtn setTitleColor:[HexChangeRGB colorWithHexString:@"#754c24"] forState:UIControlStateNormal];
    [settingBtn setTitle:NSLocalizedString(@"分享设置", nil) forState:UIControlStateNormal];
    self.navigationItem.titleView = settingBtn;
    
    UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backbtn.frame = CGRectMake(0,0,80,40);
    backbtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0f];
    backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    [backbtn setTitle:NSLocalizedString(@"返回", nil) forState:UIControlStateNormal];
    [backbtn setTitleColor:[HexChangeRGB colorWithHexString:@"#000000"] forState:UIControlStateNormal];
    [backbtn setImage: [UIImage imageNamed:@"cat_alarm_back"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(selectLeftActionClick) forControlEvents:UIControlEventTouchUpInside];
    
    [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];
    
    self.containerScrollview.backgroundColor = [UIColor whiteColor];
    self.containerView.backgroundColor = [UIColor whiteColor];
   

}

- (void)selectLeftActionClick
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark: Scrollview视图
-(UIScrollView*)containerScrollview
{
    if (!_containerScrollview) {
         _containerScrollview = [[UIScrollView alloc]init];
         _containerScrollview.backgroundColor = [UIColor whiteColor];
        if (@available(iOS 11.0, *)) {
            _containerScrollview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
        }
         _containerScrollview.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_containerScrollview];
        [_containerScrollview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
            make.width.equalTo(self.view.mas_width);
        }];
    }
    return _containerScrollview;
    
}

#pragma mark: Scrollview视图上的容纳视图
- (UIView*)containerView
{
    if (!_containerView) {
        _containerView = [[UIView alloc]init];
        [self.containerScrollview addSubview:_containerView];
        [_containerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.containerScrollview);
            make.width.equalTo(self.view.mas_width);
        }];
    }
    return _containerView;
}


- (UIView*)iconContrainview
{
    if (!_iconContrainview) {
         _iconContrainview = [[UIView alloc]init];
         _iconContrainview.userInteractionEnabled = YES;
         _iconContrainview.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
        [self.containerView addSubview:_iconContrainview];
        [_iconContrainview mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(kScreenWidth-28);
            make.height.mas_equalTo(420);
            make.centerX.equalTo(self.containerView.mas_centerX);
            make.top.equalTo(self.containerView.mas_top).offset(20);
        }];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapclick)];
        [_iconContrainview addGestureRecognizer:tap];
        // icon
        UIView *view = [[UIView alloc]init];
        view.layer.cornerRadius = 8;
        view.layer.borderColor = [HexChangeRGB colorWithHexString:@"#E6E6E6"].CGColor;
        view.layer.borderWidth = 0.5;
        view.layer.masksToBounds = YES;
        view.backgroundColor = [UIColor whiteColor];
        
        [_iconContrainview addSubview:view];
        [view mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(kScreenWidth-48);
            make.height.mas_equalTo(60);
            make.top.equalTo(_iconContrainview.mas_top);
            make.left.equalTo(_iconContrainview.mas_left).offset(14);
        }];
        
        UILabel *icon_label = [[UILabel alloc]init];
        [view addSubview:icon_label];
        icon_label.textAlignment = NSTextAlignmentCenter;
        icon_label.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
        icon_label.textColor = [HexChangeRGB colorWithHexString:@"#333333"];
       [view addSubview:icon_label];
       [icon_label mas_remakeConstraints:^(MASConstraintMaker *make) {
           make.left.equalTo(view.mas_left).offset(14);
           make.centerY.equalTo(view.mas_centerY);
       }];
        
        icon_label.text = NSLocalizedString(@"头像",nil);

        
       UIImageView *_codeImageview = [[UIImageView alloc]init];
       [view addSubview:_codeImageview];
       [_codeImageview mas_remakeConstraints:^(MASConstraintMaker *make) {
           make.height.mas_equalTo(40);
           make.width.mas_equalTo(40);
           make.centerY.equalTo(view.mas_centerY);
           make.right.equalTo(view.mas_right).offset(-14);
       }];
        _codeImageview.layer.cornerRadius = 20;
        _codeImageview.layer.masksToBounds = YES;
  
        if ([self.share_dict objectForKey:@"user_avatar"] && [NSString stringWithFormat:@"%@",[self.share_dict objectForKey:@"user_avatar"]].length > 0) {
            NSString *Firststr =  [[self.share_dict objectForKey:@"user_avatar"] substringToIndex:1];
            if ([Firststr isEqualToString:@"A"] || [Firststr isEqualToString:@"B"]) {
                [_codeImageview sd_setImageWithURL:[YKBusinessFramework equesDownloadSharingVideo:[self.share_dict objectForKey:@"user_avatar"]] placeholderImage:[UIImage imageNamed:@"ic_menu_eques_logo.png"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                }];
            }else{
                [_codeImageview sd_setImageWithURL:[NSURL URLWithString:[self.share_dict objectForKey:@"user_avatar"]] placeholderImage:[UIImage imageNamed:@"ic_menu_eques_logo.png"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                }];
            }
        }else{
            _codeImageview.image =[UIImage imageNamed:@"ic_menu_eques_logo.png"];
        }
        
        
        
        // nick
        UIView *view2 = [[UIView alloc]init];
        view2.layer.cornerRadius = 8;
        view2.layer.borderColor = [HexChangeRGB colorWithHexString:@"#E6E6E6"].CGColor;
        view2.layer.borderWidth = 0.5;
        view2.layer.masksToBounds = YES;
        view2.backgroundColor = [UIColor whiteColor];
        [_iconContrainview addSubview:view2];
        [view2 mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(kScreenWidth-48);
            make.height.mas_equalTo(60);
            make.top.equalTo(view.mas_bottom).offset(20);
            make.left.equalTo(_iconContrainview.mas_left).offset(14);
        }];
        view2.tag = 118;
        
        UILabel *nick_label = [[UILabel alloc]init];
        [view addSubview:nick_label];
        nick_label.textAlignment = NSTextAlignmentCenter;
        nick_label.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
        nick_label.textColor = [HexChangeRGB colorWithHexString:@"#333333"];
       [view2 addSubview:nick_label];
       [nick_label mas_remakeConstraints:^(MASConstraintMaker *make) {
           make.left.equalTo(view2.mas_left).offset(14);
           make.centerY.equalTo(view2.mas_centerY);
       }];
        nick_label.text = NSLocalizedString(@"昵称",nil);

        
       UITextField *_nickField = [[UITextField alloc]init];
        _nickField.textColor = [HexChangeRGB colorWithHexString:@"#9b9b9b"];
        _nickField.backgroundColor = [UIColor whiteColor];
        _nickField.delegate = self;
        _nickField.tag = 119;
        _nickField.borderStyle = UITextBorderStyleNone;
        _nickField.rightViewMode = UITextFieldViewModeAlways;
        _nickField.textAlignment = NSTextAlignmentRight;
        _nickField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _nickField.placeholder =  NSLocalizedString(@"输入昵称",nil);
       [view2 addSubview:_nickField];
       [_nickField mas_makeConstraints:^(MASConstraintMaker *make) {
           make.right.equalTo(view2.mas_right).offset(-14);
           make.centerY.equalTo(view2.mas_centerY);
           make.height.mas_equalTo(30);
       }];
    }

    return _iconContrainview;
}

- (void)tapclick
{
    NSLog(@"点击取消");
    UIView *view =(UIView*)[self.iconContrainview viewWithTag:118];
    UITextField *filed = (UITextField*) [view viewWithTag:119];
    [filed resignFirstResponder];
}



- (UIView*)bottom_view
{
    if (!_bottom_view) {
         _bottom_view = [[UIView alloc]init];
         _bottom_view.layer.cornerRadius = 8;
         _bottom_view.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
         _bottom_view.layer.masksToBounds = YES;
        [self.containerView addSubview:_bottom_view];
        [_bottom_view mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(kScreenWidth);
            make.height.mas_equalTo(300);
            make.centerX.equalTo(self.containerView.mas_centerX);
            make.top.equalTo(self.iconContrainview.mas_bottom);
            make.bottom.equalTo(self.containerView.mas_bottom);
        }];
        
       
        UIButton * _saveSettingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _saveSettingBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18.0];
       [_saveSettingBtn setTitle:NSLocalizedString(@"保存设置", nil) forState:UIControlStateNormal];
       [_saveSettingBtn setTitleColor:[HexChangeRGB colorWithHexString:@"ffffff"] forState:UIControlStateNormal];
       [_saveSettingBtn setBackgroundImage:[Tooles createImageWithColor:[HexChangeRGB colorWithHexString:@"#fb8d31"]] forState:UIControlStateNormal];
       [_saveSettingBtn setBackgroundImage:[Tooles createImageWithColor:[HexChangeRGB colorWithHexString:@"#C66A1C"]] forState:UIControlStateHighlighted];
        _saveSettingBtn.layer.cornerRadius = 25;
        _saveSettingBtn.layer.masksToBounds = YES;
       [_saveSettingBtn addTarget:self action:@selector(saveSettingBtnClick) forControlEvents:UIControlEventTouchUpInside];
       [_bottom_view addSubview:_saveSettingBtn];
       [_saveSettingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
           make.centerX.equalTo(_bottom_view.mas_centerX);
           make.height.mas_equalTo(50);
           make.width.mas_equalTo(280);
           make.top.equalTo(_bottom_view.mas_top);
       }];
      
        UIButton *_cancleShareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancleShareBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18.0];
       [_cancleShareBtn setBackgroundImage:[Tooles createImageWithColor:[UIColor clearColor]] forState:UIControlStateNormal];
       [_cancleShareBtn setBackgroundImage:[Tooles createImageWithColor:[UIColor grayColor]] forState:UIControlStateHighlighted];
        _cancleShareBtn.layer.cornerRadius = 25;
        _cancleShareBtn.layer.masksToBounds = YES;
        _cancleShareBtn.layer.borderWidth = 1;
        
       [_cancleShareBtn setTitle:NSLocalizedString(@"取消分享", nil) forState:UIControlStateNormal];
        _cancleShareBtn.layer.borderColor = [HexChangeRGB colorWithHexString:@"#ff7316"].CGColor;
       [_cancleShareBtn addTarget:self action:@selector(cancleShareBtnClick) forControlEvents:UIControlEventTouchUpInside];
       [_cancleShareBtn setTitleColor:[HexChangeRGB colorWithHexString:@"#fb8d31"] forState:UIControlStateNormal];
       [_bottom_view addSubview:_cancleShareBtn];
       [_cancleShareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
           make.centerX.equalTo(_bottom_view.mas_centerX);
           make.height.mas_equalTo(50);
           make.width.mas_equalTo(280);
           make.top.equalTo(_saveSettingBtn.mas_bottom).offset(20);
       }];
        _cancleShareBtn.titleLabel.font = [UIFont systemFontOfSize:12.0];
        
        
    }
    
    return _bottom_view;
}

- (void)saveSettingBtnClick
{
    
    UIAlertView *_saveSettingAlter = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"Whether to save a nickname?", nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", nil) otherButtonTitles:NSLocalizedString(@"sure", nil), nil];
    _saveSettingAlter.tag = 111;
   [_saveSettingAlter show];

}

- (void)cancleShareBtnClick
{
    
    UIView *view =(UIView*)[self.iconContrainview viewWithTag:118];
    UITextField *filed = (UITextField*) [view viewWithTag:119];
    [filed resignFirstResponder];
    
    UIAlertView *_cancleAlterView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"To cancel the share", nil) message:NSLocalizedString(@"Cancel after the relatives and friends will no longer use your cat's eye", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", nil) otherButtonTitles:NSLocalizedString(@"sure", nil), nil];
   _cancleAlterView.tag = 112;
  [_cancleAlterView show];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag ==  111) {
        if (buttonIndex == 0) {
             NSLog(@"取消设置昵称");
        }else if(buttonIndex == 1){
            NSString *nickname;
            
            UIView *view =(UIView*)[self.iconContrainview viewWithTag:118];
            UITextField *filed = (UITextField*) [view viewWithTag:119];
            NSString *name = filed.text;
            if (![Tooles isValidateNick:name]){ // 无效
                if (name.length == 0)
                {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"Please enter devices name", nil) delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"sure", nil), nil];
                    [alertView show];
                    return;
                }else{
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message: NSLocalizedString(@"Please input letters,number or underline.Nickname length is not more than ten characters", nil) delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"sure", nil), nil];
                    [alertView show];
                }
            }else{ //昵称有效
                if (name.length >= 10) {
                    NSRange range = {0,10};
                    nickname = [name substringWithRange:range];
                }else {
                    NSRange range = {0,name.length};
                    nickname = [name substringWithRange:range];
                }
                
                
                [AFNHTTPSRequest httpsRequestWithUrl:[YKBusinessFramework save_share_user_nickName:nickname device_id:self.bid user_id:[self.share_dict objectForKey:@"bid"]] errorHint:^(id errorData) {
                    NSLog(@"请求数据失败-->%@",errorData);
                } result:^(id data) {
                    NSDictionary *dict = (NSDictionary*)data;
                    
                    NSInteger code = [[dict objectForKey:@"code"] integerValue];
                    if (code == 0) {
                        [self.navigationController popViewControllerAnimated:YES];
                        self.navigationController.navigationBar.shadowImage = [[UIImage alloc]init];
                    }
                }];
        
                NSLog(@"保存设置昵称");
            }
         }
    }else if(alertView.tag ==  112){
        if (buttonIndex == 0) {
            NSLog(@"不取消分享设置");
        }else if(buttonIndex == 1){
            NSLog(@"取消分享设置");
            
            [SVProgressHUD showWithStatus:NSLocalizedString(@"Canceling…,please wait", nil) duration:10 completionBlock:^{
                
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Operation failed", nil)];
            }];
    
            
            [AFNHTTPSRequest httpsRequestWithUrl:[YKBusinessFramework cancel_share_device:self.bid userid:[self.share_dict objectForKey:@"bid"]] errorHint:^(id errorData) {
                [SVProgressHUD dismiss];
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Operation failed", nil)];
            } result:^(id data) {
                
                [SVProgressHUD dismiss];
                 NSDictionary *dict = (NSDictionary*)data;
                NSInteger code = [[dict objectForKey:@"code"] integerValue];
                if (code == 0) {
                    [self.navigationController popViewControllerAnimated:YES];
                }
                
            }];
        }
    }
}

// 代理方法：当点击键盘上的 "Return" 或 "完成" 按钮时调用
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    // 收起键盘
    [textField resignFirstResponder];
    
    // 在这里处理点击完成后的操作
    NSLog(@"点击了完成按钮");
    
    return YES;
}


@end
